<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input
            v-model="listQuery.id"
            placeholder="关键词过滤"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"/>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索
          </el-button>
          <el-button
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="handleCreate">新增
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          :height="tableHeight"
          element-loading-text="Loading"
          border
          fit
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <el-table-column label="红包名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.bonusName }}
            </template>
          </el-table-column>
          <el-table-column label="红包金额" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.bonusMoney }}
            </template>
          </el-table-column>
          <el-table-column label="发送类型" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.sendType | sendTypeFilter }}
            </template>
          </el-table-column>
          <el-table-column label="会员等级" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.rankName }}
            </template>
          </el-table-column>
          <!--<el-table-column label="红包图片" show-overflow-tooltip style="width: 10%" align="center">-->
            <!--<template slot-scope=          <el-table-column label="订单下限" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.minGoodsAmount }}
            </template>
          </el-table-column>"scope">-->
              <!--{{ scope.row.bonusImg }}-->
            <!--</template>-->
          <!--</el-table-column>-->
          <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button v-if="scope.row.sendType == 1" size="mini" type="primary" @click="handleSendRank(scope.row)">
                发送
              </el-button>
              <el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.pageNum"
          :limit.sync="listQuery.pageSize"
          layout="total, sizes, prev, pager, next"
          style="float:right;"
          @pagination="fetchData"/>
      </el-col>
    </el-row>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="80%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包名称" label-width="150px" prop="bonusName">
              <el-input v-model="temp.bonusName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="红包所值金额" label-width="150px" prop="bonusMoney">
              <el-input v-model.number="temp.bonusMoney"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单最少金额" label-width="150px" prop="minGoodsAmount">
              <el-input v-model="temp.minGoodsAmount"/>
            </el-form-item>
          </el-col>
          <!--<el-col :span="12">-->
            <!--<el-form-item label="红包图片" label-width="150px" prop="bonusImg">-->
              <!--<el-upload-->
                <!--:show-file-list="false"-->
                <!--:on-success="handleAvatarSuccess"-->
                <!--:before-upload="beforeAvatarUpload"-->
                <!--:action="uploadUrl"-->
                <!--class="avatar-uploader">-->
                <!--<img v-if="temp.bonusImg" :src="temp.bonusImg" class="avatar">-->
                <!--<i v-else class="el-icon-plus avatar-uploader-icon"/>-->
              <!--</el-upload>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="红包可用产品" label-width="150px" prop="useGoods">
              <el-transfer v-model="selectUseGoods" :props="{key: 'pid',label: 'pname'}" :data="productData"/>
              <span style="color: red">没选为所有产品可用</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="红包发送类型" label-width="150px" prop="sendType">
              <el-radio-group v-model.number="temp.sendType" :disabled="dialogStatus == 'update'">
                <el-radio v-for="( value,key ) in sendTypeMap" :label="parseInt(key)" :key="key">{{ value }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="temp.sendType === 2" :gutter="20">
          <el-col :span="12">
            <el-form-item label="发送红包的时间" label-width="150px" prop="sendStartDate">
              <el-date-picker
                v-model="temp.sendStartDate"
                type="date"
                value-format="timestamp"
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送红包结束时间" label-width="150px" prop="sendEndDate">
              <el-date-picker
                v-model="temp.sendEndDate"
                type="date"
                value-format="timestamp"
                placeholder="选择日期"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="红包有效天数" label-width="150px" prop="useEndDate">
              <el-input v-model.number="temp.expireDay"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="排序" label-width="150px" prop="sort">
          <el-input v-model.number="temp.sort"/>
          </el-form-item>
          </el-col>
          <!--<el-col :span="12">-->
            <!--<el-form-item label="红包个数" label-width="150px" prop="bonusNumber">-->
              <!--<el-input v-model.number="temp.bonusNumber"/>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-row v-if= "temp.sendType == 2" :gutter="20">
          <el-col :span="12">
            <el-form-item label="所需要的积分" label-width="150px" prop="costPoint">
              <el-input v-model.number="temp.costPoint"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 发送红包给等级 -->
    <el-dialog
      :visible.sync="sendRankVisible"
      title="发送红包"
      width="80%">
      <el-form
        ref="dataForm1"
        :model="rank"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="红包名称" label-width="150px">
              <el-input v-model="rank.bonusName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="请选择等级" label-width="150px" prop="id">
              <el-radio-group v-model="rank.id">
                <el-radio v-for="tempRank in rankList" :key="tempRank.id" :label="tempRank.id">{{ tempRank.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendRank()">确认</el-button>
        <el-button @click="sendRankVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import SxBoundTypeApi from '@/api/manage/SxBoundTypeApi'
import sxProductBasicInfoApi from '@/api/manage/SxProductBasicInfoApi'
import SxUserRankApi from '@/api/manage/SxUserRankApi'
import waves from '@/directive/waves' // Waves directive
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  directives: { waves },
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'gray',
        0: 'danger'
      }
      return statusMap[status]
    },
    validFilter(status) {
      const statusMap = {
        1: '有效',
        0: '作废'
      }
      return statusMap[status]
    },
    timeFilter(time) {
      if (time) {
        return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    },
    sendTypeFilter(sendType) {
      const sendTypeMap = {
        1: '会员级别发送',
        2: '积分兑换',
        3: '分享有礼',
        4: '至美传递'
      }
      if (sendType) {
        return sendTypeMap[sendType]
      }
      return ''
    }
  },
  data() {
    return {
      tableKey: 0, // 表格key值
      list: null, // 表格对象
      listLoading: true, // 表格加载框
      total: 0, // 分页总数
      tableHeight: window.innerHeight - 220, // 表格高度
      listQuery: { // 表格查询对象
        pageNum: 1,
        pageSize: 10,
        query: '',
        validFlag: undefined,
        id: ''
      },
      temp: {}, // 编辑框临时变量
      statusOptions: { // 有效无效下拉框
        '1': '有效',
        '0': '作废'
      },
      dialogFormVisible: false, // 编辑框显示
      dialogStatus: '', // 编辑框更新插入状态
      textMap: { // 编辑框标题
        update: '编辑',
        create: '创建'
      },
      rules: { // 编辑框校验规则
        sxBoundTypeName: [{ required: true, message: '红包管理名称', trigger: 'change' }]
      },
      productData: [],
      selectUseGoods: [],
      sendTypeMap: {
        1: '会员级别发送',
        2: '积分兑换',
        3: '分享有礼',
        4: '至美传递'
      },
      uploadUrl: process.env.BASE_API + '/file/upload',
      rank: {

      },
      rankList: [],
      sendRankVisible: false
    }
  },
  computed: {
    validSwitch: {
      // getter
      get: function() {
        return this.temp.validFlag === '1'
      },
      // setter
      set: function(newValue) {
        if (newValue) {
          this.temp.validFlag = '1'
        } else {
          this.temp.validFlag = '0'
        }
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    /**
       * 获取顶级结点
       * */
    getRootData() {
      sxProductBasicInfoApi.getRootData({ r: Math.random() }).then((data) => {
        this.productData = data
      })
    },
    /**
       * 获取表格数据
       */
    fetchData() {
      const that = this
      this.listLoading = true
      this.$http.all([SxBoundTypeApi.getPage(this.listQuery)])
        .then(this.$http.spread(function(perms) {
          that.list = perms.rows
          that.total = perms.total
          that.listLoading = false
        }))
    },
    /**
       * 新增弹窗
       */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.selectUseGoods = []
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getRootData()
    },
    /**
       * 清空弹窗内容
       */
    resetTemp() {
      this.temp = {
        id: '',
        bonusName: '',
        bonusType: '',
        bonusMoney: 0,
        useGoods: '',
        sendType: 1,
        sendStartDate: '',
        sendEndDate: '',
        useStartDate: '',
        useEndDate: '',
        minGoodsAmount: 0,
        bonusNumber: 0,
        bonusImg: '',
        validFlag: '1',
        expireDay: 15,
        costPoint: 0,
        sort: 1
      }
    },
    /**
       * 确定新增
       */
    createData() {
      const that = this
      this.temp.useGoods = JSON.stringify(this.selectUseGoods)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          SxBoundTypeApi.insert(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 编辑弹窗
       */
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.getRootData()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      if (this.temp.useGoods) {
        this.selectUseGoods = JSON.parse(this.temp.useGoods)
      }
    },
    /**
       * 确认编辑
       */
    updateData() {
      const that = this
      this.temp.useGoods = JSON.stringify(this.selectUseGoods)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          SxBoundTypeApi.update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 删除操作
       */
    handleDelete(row) {
      const that = this
      SxBoundTypeApi.remove({ id: row.id }).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 1000,
          onClose() {
            that.fetchData()
          }
        })
      })
    },
    /**
       *  重置rank
       */
    resetRank() {
      this.rank = {
        id: '',
        bonusId: '',
        bonusName: ''
      }
    },
    handleSendRank(row) {
      this.resetRank()
      this.getRankList()
      this.rank.id = ''
      this.rank.bonusId = row.id
      this.rank.bonusName = row.bonusName
      this.sendRankVisible = true
    },
    getRankList() {
      SxUserRankApi.getList({}).then((data) => {
        this.rankList = data
        if (data) {
          for (let i = 0; i < data.length; i++) {
            const temp = data[i]
            if (temp.bonusId === this.rank.bonusId) {
              this.rank.id = temp.id
            }
          }
        }

      })
    },
    sendRank() {
      const that = this
      this.$refs['dataForm1'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rank)
          SxUserRankApi.update(tempData).then(() => {
            this.sendRankVisible = false
            this.$notify({
              title: '成功',
              message: '发送成功',
              type: 'success',
              duration: 1000,
              onClose() {
                that.fetchData()
              }
            })
          })
        }
      })
    },
    /**
       * 搜索过滤
       */
    handleFilter() {
      this.listQuery.pageNum = 1
      this.fetchData()
    },
    handleAvatarSuccess(res, file) {
      this.temp.bonusImg = res.data[0]
    },

    beforeAvatarUpload(file) {
      debugger
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>
